import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';

import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { MaxLengthValidators, MinLengthValidators, PhoneValidators } from '../../../common/common.validators';
import { SunshineNgZorroAntdModule } from '../../../ng-zorro-module';

@Component({
  selector: 'nz-demo-form-auto-tips',
  template: `
    <form nz-form [nzAutoTips]="autoTips" [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>用户名</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidatingTip="校验中...">
          <input nz-input formControlName="userName" placeholder="发起异步请求校验用户名" />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>手机号</nz-form-label>
        <nz-form-control [nzSpan]="12">
          <input nz-input formControlName="mobile" placeholder="请输入手机号"   />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>邮箱</nz-form-label>
        <nz-form-control [nzSpan]="12">
          <input nz-input formControlName="email" placeholder="请输入邮件地址" type="email" />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>密码</nz-form-label>
        <nz-form-control [nzSpan]="12" nzDisableAutoTips nzErrorTip="请输入正确的密码!">
          <!-- 数据改变时触发校验 -->
          <input nz-input type="password" formControlName="password" (ngModelChange)="validateConfirmPassword()" />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label [nzSpan]="7" nzRequired>确认密码</nz-form-label>
        <nz-form-control [nzSpan]="12" nzDisableAutoTips [nzErrorTip]="passwordErrorTpl">
          <input nz-input type="password" formControlName="confirm" placeholder="确认密码" />
          <ng-template #passwordErrorTpl let-control>
            <ng-container *ngIf="control.hasError('required')">请输入你的密码!</ng-container>
            <ng-container *ngIf="control.hasError('confirm')">请保持密码一致!</ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control [nzOffset]="7" [nzSpan]="12">
          <button nz-button nzType="primary" >提交</button>
        </nz-form-control>
      </nz-form-item>
    </form>
     <nz-form-control [nzOffset]="7"  >
          <button nz-button nzType="default" (click)="submitForm()" >提交</button>
        </nz-form-control>
  `,
  styles: [
    `
      [nz-form] {
        max-width: 600px;
      }
    `
  ], standalone: true,
  imports: [SunshineNgZorroAntdModule]
})
export class NzDemoFormAutoTipsComponent {

  validateForm: FormGroup;

  autoTips: Record<string, Record<string, string>> = {
    'zh-cn': {
      required: '必填项'
    },
    en: {
      required: 'Input is required'
    },
    default: {
      email: '邮箱格式不正确/The input is not valid email'
    }
  };

  // 表单提交
  submitForm(): void {
    console.log('表单提交前的校验 this.validateForm.valid = ' + this.validateForm.valid)
    // 校验通过才能提交数据
    if (this.validateForm.valid) {
      console.log('submit的数据', this.validateForm.value);
      let { userName } = this.validateForm.value;
      console.log(userName)
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 验证密码
  validateConfirmPassword(): void {
    console.log('开始密码验证')
    setTimeout(() => this.validateForm.controls['confirm'].updateValueAndValidity());
  }

  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
  // 异步验证用户名
  userNameAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<MyValidationErrors | null>) => {
      console.log(control.value)
      console.log(control.validator)
      console.log(control.valid)
      setTimeout(() => {
        if (control.value === 'JasonWood') {
          observer.next({
            duplicated: { 'zh-cn': `用户名已存在`, en: `The username is redundant!` }
          });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  // 自定义验证器
  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    //  获取输入的值
    if (!control.value) {
      // 返回校验失败
      return { error: true, required: true };
    } else if (control.value !== this.validateForm.controls['password'].value) { // 比较两次输入的密码是否一致
      return { confirm: true, error: true };
    }
    return {};
  };

  constructor(private fb: FormBuilder) {
    // use `MyValidators`
    // const { required, maxLength, minLength, email, mobile } = MyValidators;
    this.validateForm = this.fb.group({
      // 设置校验规则 初始值 规则  失去焦点校验
      userName: ['', [Validators.required, MaxLengthValidators.maxLength(12), MinLengthValidators.minLength(6)], [this.userNameAsyncValidator], 'blur'],
      mobile: ['', [Validators.required, PhoneValidators.mobile]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required]],
      confirm: ['', [this.confirmValidator]]
    });

    // 设置初始值
    this.validateForm.setValue({ userName: 'zhangsan', mobile: '15934569842', email: '12341231421@qq.com', password: '123456', confirm: '123456' })
  }
}

// current locale is key of the MyErrorsOptions
export type MyErrorsOptions = { 'zh-cn': string; en: string } & Record<string, NzSafeAny>;
export type MyValidationErrors = Record<string, MyErrorsOptions>;



